//
//  ByLoginVC.m
//  recordworktool_ios
//
//  Created by mc on 2017/12/4.
//  Copyright © 2017年 ZhangZhanbin. All rights reserved.
//

#import "ByLoginVC.h"
#import "ByTabBarController.h"
@interface ByLoginVC (){
    NSInteger _countTime;
}
@property (nonatomic, strong) UITextField *phoneTF;
@property (nonatomic, strong) UITextField *codeTF;

@property (nonatomic, strong) UIButton *codeBtn;

@end

@implementation ByLoginVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //[self addLeftBackBarButtonItem];
    self.title = @"登录";
    
    [self initViews];
    // Do any additional setup after loading the view.
}

- (void)initViews{
    
    UITextField *phoneTF = [[UITextField alloc] init];
    [self.view addSubview:phoneTF];
    [phoneTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(10);
        make.right.equalTo(self.view).offset(-10);
        make.top.equalTo(self.view).offset(30);
        make.height.mas_equalTo(@55);
    }];
    phoneTF.placeholder = @"您的手机号";
    phoneTF.layer.cornerRadius = 10;
    phoneTF.layer.borderColor = BY_LINE_COLOR.CGColor;
    phoneTF.layer.borderWidth = 1.5;
    phoneTF.keyboardType = UIKeyboardTypeNumberPad;
    
    UILabel *phoneLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 80, 20)];
    phoneLabel.text = @"手机号";
    phoneLabel.font = FONT(16);
    phoneLabel.textColor = TEXT_COLOR;
    phoneLabel.textAlignment = NSTextAlignmentCenter;
    phoneTF.leftView = phoneLabel;
    phoneTF.leftViewMode = UITextFieldViewModeAlways;
    
    
    UITextField *codeTF = [[UITextField alloc] init];
    [self.view addSubview:codeTF];
    [codeTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(10);
        make.right.equalTo(self.view).offset(-10);
        make.top.equalTo(phoneTF.mas_bottom).offset(15);
        make.height.mas_equalTo(@55);
    }];
    codeTF.placeholder = @"您收到的验证码";
    codeTF.layer.cornerRadius = 10;
    codeTF.layer.borderColor = BY_LINE_COLOR.CGColor;
    codeTF.layer.borderWidth = 1.5;
    
    UILabel *codeLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 80, 20)];
    codeLabel.text = @"验证码";
    codeLabel.font = FONT(16);
    codeLabel.textColor = TEXT_COLOR;
    codeLabel.textAlignment = NSTextAlignmentCenter;
    codeTF.leftView = codeLabel;
    codeTF.leftViewMode = UITextFieldViewModeAlways;
    
    
    UIButton *sendBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    sendBtn.frame = CGRectMake(0, 0, 120, 20);
    [sendBtn setTitle:@"发送验证码" forState:UIControlStateNormal];
    [sendBtn setTitleColor:BY_THEME_COLOR forState:UIControlStateNormal];
    sendBtn.titleLabel.font = FONT(14);
    [sendBtn addTarget:self action:@selector(sendAction:) forControlEvents:UIControlEventTouchUpInside];
    phoneTF.rightView = sendBtn;
    phoneTF.rightViewMode = UITextFieldViewModeAlways;
    self.codeBtn = sendBtn;
    
   
    
    UIButton *loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:loginBtn];
    [loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(codeTF.mas_bottom).offset(40);
        make.left.equalTo(self.view).offset(10);
        make.right.equalTo(self.view).offset(-10);
        make.height.mas_equalTo(@60);
    }];
    loginBtn.layer.cornerRadius = 30;
    loginBtn.backgroundColor = BY_THEME_COLOR;
    [loginBtn setTitle:@"登录" forState:UIControlStateNormal];
    [loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [loginBtn addTarget:self action:@selector(loginAction:) forControlEvents:UIControlEventTouchUpInside];
    
    
    UIButton *otherBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:otherBtn];
    [otherBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view).offset(-40);
        make.top.equalTo(loginBtn.mas_bottom).offset(10);
        make.size.mas_equalTo(CGSizeMake(70, 20));
    }];
    otherBtn.titleLabel.font = FONT(16);
    [otherBtn setTitleColor:BY_THEME_COLOR forState:UIControlStateNormal];
    [otherBtn setTitle:@"工头登录" forState:UIControlStateNormal];
    [otherBtn addTarget:self action:@selector(otherAction:) forControlEvents:UIControlEventTouchUpInside];
    
    self.phoneTF = phoneTF;
    self.codeTF = codeTF;
    
}

- (void)otherAction:(UIButton *)btn{
    NSLog(@"工头登录");
    
    if (self.phoneTF.text.length != 11) {
        [ByCoreToolAlert showOnlyText:@"请输入正确的手机号"];
        return;
    }
    
    if (self.codeTF.text.length  == 0) {
        [ByCoreToolAlert showOnlyText:@"请输入验证码"];
        return;
    }
    
    ByNetParamsModel *paramsModel = [[ByNetParamsModel alloc] init];
    paramsModel.mobile = self.phoneTF.text;
    paramsModel.code = self.codeTF.text;
    paramsModel.role = @"13";
    [ByCoreToolAlert showLoadind:@"登录中" hasMasker:YES];
    [ByApiUser login:paramsModel success:^(ByNetBaseResult *result) {
        
        [ByCoreToolAlert showSuccessWithText:@"登录成功"];
        ByModelUser *modelUser = (ByModelUser *)result.data;
        modelUser.isWorker = @"0";//工头
        // 缓存用户model
        [ByCacheUser setUserInfo:modelUser];
        
        // 友盟设置别名
        NSString *alisa = [NSString stringWithFormat:@"%@", modelUser.uid];
        [UMessage addAlias:alisa type:@"com.itboye.jigongbao" response:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
            if (error) {
                NSString *str = error.domain;
                printf("别名绑定_error:%s", [str UTF8String]);
            } else {
                printf("别名绑定成功");
            }
        }];

        
        
        [self dismissViewControllerAnimated:YES completion:nil];
        
        if (self.needReload) {
            UIWindow *window = [UIApplication sharedApplication].keyWindow;
            window.rootViewController = [[ByTabBarController alloc] init];
        }
        
        
    } failure:^(ByNetBaseResult *result) {
        [ByCoreToolAlert showFailureWithText:result.msg];
    }];
}


- (void)loginAction:(UIButton *)btn{
    NSLog(@"登录");
    if (self.phoneTF.text.length != 11) {
        [ByCoreToolAlert showOnlyText:@"请输入正确的手机号"];
        return;
    }
    
    if (self.codeTF.text.length  == 0) {
        [ByCoreToolAlert showOnlyText:@"请输入验证码"];
        return;
    }
    ByNetParamsModel *paramsModel = [[ByNetParamsModel alloc] init];
    paramsModel.mobile = self.phoneTF.text;
    paramsModel.code = self.codeTF.text;
    paramsModel.role = @"14";
    [ByCoreToolAlert showLoadind:@"登录中" hasMasker:YES];
    [ByApiUser login:paramsModel success:^(ByNetBaseResult *result) {
        
        [ByCoreToolAlert showSuccessWithText:@"登录成功"];
        ByModelUser *modelUser = (ByModelUser *)result.data;
        modelUser.isWorker = @"1";//工人
        // 缓存用户model
        [ByCacheUser setUserInfo:modelUser];
        
        // 友盟设置别名
        NSString *alisa = [NSString stringWithFormat:@"%@", modelUser.uid];
        [UMessage addAlias:alisa type:@"com.itboye.jigongbao" response:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
            if (error) {
                NSString *str = error.domain;
                printf("别名绑定_error:%s", [str UTF8String]);
            } else {
                printf("别名绑定成功");
            }
        }];
        
        [self dismissViewControllerAnimated:YES completion:nil];
        
        if (self.needReload) {
            UIWindow *window = [UIApplication sharedApplication].keyWindow;
            window.rootViewController = [[ByTabBarController alloc] init];
        }
        
        
    } failure:^(ByNetBaseResult *result) {
        [ByCoreToolAlert showFailureWithText:result.msg];
    }];
    
}

- (void)sendAction:(UIButton *)btn{
    NSLog(@"发送验证码");
    if (self.phoneTF.text.length != 11) {
        [ByCoreToolAlert showOnlyText:@"请输入正确的手机号"];
        return;
    }
    
    ByNetParamsModel *paramsModel = [[ByNetParamsModel alloc] init];
    [ByCoreToolAlert showLoadind:@"验证码发送中"];
    paramsModel.mobile = self.phoneTF.text;
    [ByApiUser sendCode:paramsModel success:^(ByNetBaseResult *result) {
        //禁止点击
        btn.enabled = NO;
        _countTime = 60;
        if ([self.phoneTF.text isEqualToString:@"13136167925"]) {
            [ByCoreToolAlert hideHud];
            self.codeTF.text = result.data;
        }else{
             [ByCoreToolAlert showSuccessWithText:result.data];
        }
        NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(_countdownAction:) userInfo:nil repeats:YES];
        [timer fire];
        
    } failure:^(ByNetBaseResult *result) {
        [ByCoreToolAlert showFailureWithText:result.msg];
    }];
    
}



- (void)_countdownAction:(NSTimer *)timer{
    if (_countTime > 0){
        
        _countTime --;
        [_codeBtn setTitle:[NSString stringWithFormat:@"(%ld)重新获取", (long)_countTime] forState:UIControlStateNormal];
        
    }else {
        
        _codeBtn.enabled = YES;
        [timer invalidate];
        [_codeBtn setTitle:@"发送验证码" forState:UIControlStateNormal];
        
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
